<?php

use App\Models\Common\MsdTicket;
use App\Models\Common\MsdMember;

/**
 * @param $uid
 * @param $request
 * @return mixed
 */
function login($uid, $request)
{
    $clientUserTicket = new MsdTicket();
    $token = $clientUserTicket->login($uid, $request);
    $data = $clientUserTicket
        ->select('uid')
        ->where(['ticket' => $token['ticket']])
        ->first();
    $data->mobile = MsdMember::where(['member_id' => $data->uid])->value('cellphone');
    $data->mobile_hidden = hidden_mobile($data->mobile);
    $data->token = $token['token'];
    return $data;
}

/**
 * 时间戳格式化成国内日期格式
 * @param int|null $time
 * @return false|string
 */
function time2date($time = null)
{
    return date('Y-m-d H:i:s', $time ?? (int)request()->server('REQUEST_TIME'));
}

function time2date_date($time = null)
{
    return date('Y-m-d', $time ?? (int)request()->server('REQUEST_TIME'));
}

/******************************************************** 隐藏数据部分 *******************************************************/
/**
 * @param $mobile
 * @return string
 */
function hidden_mobile($mobile)
{
    $pre = substr($mobile, 0, 3);
    $last = substr($mobile, 7);
    return $pre . '****' . $last;
}


/******************************************************** 接口通用返回部分 **************************************************/

/**
 * @param string|array $data
 * 清楚数据内的null
 */
function clear_null(&$data = '')
{
    $data = json_decode(json_encode($data), true);
    if ($data === null || $data === false) {
        $data = '';
    }
    if (is_array($data) && !empty($data)) {
        foreach ($data as &$v) {
            if ($v === null || $v === false) {
                $v = '';
            } else if (is_array($v)) {
                clear_null($v);
            } else if (is_string($v) && stripos($v, '.') === 0) {
                $v = '0' . $v;
            }
        }
    }
}

function del_null(&$data = '')
{
//	if($data instanceof stdClass){
    $data = json_decode(json_encode($data), true);
//	}
    if ($data === null || $data === false) {
        $data = '';
    }
    if (is_array($data) && !empty($data)) {
        foreach ($data as $key => &$v) {
            if ($v === null || $v === false) {
                unset($data[$key]);
            } else if (is_array($v)) {
                clear_null($v);
            } else if (is_string($v) && stripos($v, '.') === 0) {
                $v = '0' . $v;
            }
        }
    }
}

/**
 * json API 返回成功
 * @param string $msg
 * @param mixed $data
 * @return array
 */
function json_success($msg = 'OK', $data = [])
{
    $return = [
        'status_code' => '200',
        'message' => $msg,
        'data' => $data,
        //'request_uri' => request('_cmd'),
    ];
    clear_null($return['data']);
    return $return;
}

function json_success_api($data = [], $msg = 'OK')
{
    $return = [
        'status_code' => '200',
        'message' => $msg,
        'data' => $data,
        //'request_uri' => request('_cmd'),
    ];
    clear_null($return['data']);
    return $return;
}


/**
 * json API 返回失败
 * @param $msg
 * @param mixed $data
 * @param $status_code
 * @return array
 */
function json_error($msg, $data = [], $status_code = '500')
{
    $msg = $msg ?: '服务器错误，请稍后重试';
    $return = [
        'status_code' => $status_code,
        'message' => $msg,
        'data' => $data,
        //'request_uri' => request('_cmd'),
    ];
    clear_null($return['data']);
    return $return;
}



/**
 * 根据CODE返回对应状态
 * @param $code
 */
function json_code($code, $message = null)
{
    $return = getMessage($code);
    abort($return['code'], $message ? $message : $return['message']);
}

function getMessage($code)
{
    $array = [
        '10000' => array('code' => 401, 'message' => '登陆已失效'),
        '10001' => array('code' => 403, 'message' => '暂无权限'),
        '10002' => array('code' => 401, 'message' => '找不到用户'),
        '10003' => array('code' => 403, 'message' => '等待审核中'),
        '10004' => array('code' => 403, 'message' => '审核失败'),
    ];
    if ($code) {
        return $array[$code];
    } else {
        return $array;
    }
}

/********************************************************* 数据库方法封装部分 **************************************************/

/**
 * @param $field
 * @return string
 * mysql 时间戳查询时转成 timestamp 格式
 */
function from_unixtime($field)
{
    return 'from_unixtime(' . $field . ',\'%Y-%m-%d %H:%i:%s\') as ' . $field;
}

/*********************************************************** 随机数部分 **********************************************************/

/**
 * 生成一个随机数字字符串，可用于验证码等
 * @param int $length
 * @return string
 */
function create_verify_code($length = 4)
{
    $rand = [];
    for ($i = 0; $i < $length; $i++) {
        $rand[] = rand(0, 9);
    }
    $rand_str = implode('', $rand);
    return $rand_str;
}

/**
 * @return string
 * 生成唯一guid规则的字符串
 */
function uuid()
{
    if (function_exists('com_create_guid')) {
        $uuid = com_create_guid();
    } else {
        // mt_srand(( double )microtime() * 10000); //optional for php 4.2.0 and up.随便数播种，4.2.0以后不需要了。
        $charid = strtoupper(md5(uniqid((string)rand(), true))); //根据当前时间（微秒计）生成唯一id.
        $hyphen = chr(45); // "-"
        $uuid = '' . //chr(123)// "{"
            substr($charid, 0, 8) . $hyphen . substr($charid, 8, 4) . $hyphen . substr($charid, 12, 4) . $hyphen . substr($charid, 16, 4) . $hyphen . substr($charid, 20, 12);
        //.chr(125);// "}"
    }
    return str_replace(['{', '}'], ['', ''], $uuid);
}


/**
 * @param $data
 * @return mixed
 * 把数据库查询/自由拼接的数据统一转成数组
 */
function to_array($data)
{
    $return = json_decode(json_encode($data), true);
    return $return;
}

/**
 * @param $date
 * @param int $type
 * @return null|string
 * 获取传入的时间
 */
function getInputData($date, $type = 1)
{
    if (!empty($date)) {
        if ($type == 1)
            return date('Y-m-d', strtotime($date[0])) . ' 00:00:00';
        else if ($type == 2)
            return date('Y-m-d', strtotime($date[1])) . ' 23:59:59';
    }
    return null;
}

//
// [http 调用接口函数]
// @param  string       $url     [接口地址]
// @param  array        $params  [数组]
// @param  string       $method  [GET\POST\DELETE\PUT]
// @param  array        $header  [HTTP头信息]
// @param  integer      $timeout [超时时间]
// @return [type]                [接口返回数据]
///
function http($url, $params, $method = 'GET', $header = array(), $timeout = 20)
{
    // POST 提交方式的传入 $set_params 必须是字符串形式
    $opts = array(
        CURLOPT_TIMEOUT => $timeout,
        CURLOPT_RETURNTRANSFER => 1,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_SSL_VERIFYHOST => false,
        CURLOPT_SSLVERSION => 1,
        CURLOPT_FOLLOWLOCATION => 1,
        CURLOPT_HTTPHEADER => $header
    );

    if (is_array($params)) {
        $params = http_build_query($params);
    }
    /* 根据请求类型设置特定参数 */
    switch (strtoupper($method)) {
        case 'GET':
            if ($params) {
                $url = $url . '?' . $params;
            }
            $opts[CURLOPT_URL] = $url;
            break;
        case 'POST':
            $opts[CURLOPT_URL] = $url;
            $opts[CURLOPT_POST] = 1;
            $opts[CURLOPT_POSTFIELDS] = $params;
            break;
        case 'DELETE':
            $opts[CURLOPT_URL] = $url;
            $opts[CURLOPT_HTTPHEADER] = array("X-HTTP-Method-Override: DELETE");
            $opts[CURLOPT_CUSTOMREQUEST] = 'DELETE';
            $opts[CURLOPT_POSTFIELDS] = $params;
            break;
        case 'PUT':
            $opts[CURLOPT_URL] = $url;
            $opts[CURLOPT_POST] = 0;
            $opts[CURLOPT_CUSTOMREQUEST] = 'PUT';
            $opts[CURLOPT_POSTFIELDS] = $params;
            break;
        default:
            throw new \Exception('不支持的请求方式！');
    }

    /* 初始化并执行curl请求 */
    $ch = curl_init();
    curl_setopt_array($ch, $opts);
    $data = curl_exec($ch);
    $error = curl_error($ch);
    return $data;
}

//
// [http curl句柄设置并返回]
// @param  string       $url     [接口地址]
// @param  array        $params  [数组]
// @param  string       $method  [GET\POST\DELETE\PUT]
// @param  array        $header  [HTTP头信息]
// @param  integer      $timeout [超时时间]
// @return [type]                [返回curl操作句柄]
//
function getCurl($url, $params = '', $method = 'GET', $header = array(), $timeout = 20)
{
    // POST 提交方式的传入 $set_params 必须是字符串形式
    $opts = array(
        CURLOPT_TIMEOUT => $timeout,
        CURLOPT_RETURNTRANSFER => 1,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_SSL_VERIFYHOST => false,
        CURLOPT_SSLVERSION => 1,
        CURLOPT_HTTPHEADER => $header
    );

    if (is_array($params)) {
        $params = http_build_query($params);
    }
    /* 根据请求类型设置特定参数 */
    switch (strtoupper($method)) {
        case 'GET':
            if ($params) {
                $url = $url . '?' . $params;
            }
            $opts[CURLOPT_URL] = $url;
            break;
        case 'POST':
            $opts[CURLOPT_URL] = $url;
            $opts[CURLOPT_POST] = 1;
            $opts[CURLOPT_POSTFIELDS] = $params;
            break;
        case 'DELETE':
            $opts[CURLOPT_URL] = $url;
            $opts[CURLOPT_HTTPHEADER] = array("X-HTTP-Method-Override: DELETE");
            $opts[CURLOPT_CUSTOMREQUEST] = 'DELETE';
            $opts[CURLOPT_POSTFIELDS] = $params;
            break;
        case 'PUT':
            $opts[CURLOPT_URL] = $url;
            $opts[CURLOPT_POST] = 0;
            $opts[CURLOPT_CUSTOMREQUEST] = 'PUT';
            $opts[CURLOPT_POSTFIELDS] = $params;
            break;
        default:
            throw new \Exception('不支持的请求方式！');
    }

    /* 初始化并执行curl请求 */
    $ch = curl_init();
    curl_setopt_array($ch, $opts);
    return $ch;
    // $data = curl_exec($ch);
    // $error = curl_error($ch);

}

//https 发起get多发请求
function httpMulti($nodes)
{
    $mh = curl_multi_init();
    foreach ($nodes as $i => $curl) {
        curl_multi_add_handle($mh, $curl);
    }
    $running = NULL;
    do {
        usleep(10000);
        curl_multi_exec($mh, $running);
    } while ($running > 0);

    $res = array();
    foreach ($nodes as $i => $curl) {
        $res[$i] = curl_multi_getcontent($curl);
    }

    foreach ($nodes as $i => $curl) {
        curl_multi_remove_handle($mh, $curl);
    }
    curl_multi_close($mh);
    return $res;
}

function func_substr_replace($str, $replacement = '*', $start = 1, $length = 3)
{
    $len = mb_strlen($str, 'utf-8');
    if ($len > intval($start + $length)) {
        $str1 = mb_substr($str, 0, $start, 'utf-8');
        $str2 = mb_substr($str, intval($start + $length), NULL, 'utf-8');
    } else {
        $str1 = mb_substr($str, 0, 1, 'utf-8');
        $str2 = mb_substr($str, $len - 1, 1, 'utf-8');
        $length = $len - 2;
    }
    $new_str = $str1;
    for ($i = 0; $i < $length; $i++) {
        $new_str .= $replacement;
    }
    $new_str .= $str2;

    return $new_str;
}

//密码加密
function password_encode($password, $salt)
{
    if (!$salt) {
        $password_gen = md5(trim($password));
    } else {
        $password_gen = md5(md5(trim($password)) . $salt);
    }
    return $password_gen;
}

/**
 * 高精度重复相加
 * @param $scale
 * @param mixed ...$number
 * @return int|string
 */
function bcaddAll($scale, ...$number)
{
    $all = 0;
    foreach ($number as $n) {
        $all = bcadd($all, $n, $scale);
    }
    return $all;
}

/**
 * @param $double
 * @return string
 * 返回2位数的金额数据
 */
function numberFormat($double)
{
    return number_format((float)$double, 2, '.', '');
}

/**
 * @param $time
 * @param $type =1开始,=2结束
 * @return false|string
 */
function getReportTime($time, $type)
{
    if ($time) {
        $time = is_numeric($time) ? $time : strtotime($time);
        if ($type == 1) {
            return date('Y-m-d 00:00:00', $time);
        } else {
            if ($time < 946656000) {
                return date('Y-m-d 23:59:59');
            }
            return date('Y-m-d 23:59:59', $time);
        }
    }
    return false;
}

/**
 * stdClass对象转换为数组
 * @param $stdClass
 * @return mixed
 */
function convertStdToArray($stdClass)
{
    return json_decode(json_encode($stdClass), true);
}

if (! function_exists('resolve')) {
    /**
     * Resolve a service from the container.
     *
     * @param  string  $name
     * @return mixed
     */
    function resolve($name)
    {
        return app($name);
    }
}
if (! function_exists('xml_success')) {
    /**
     * return xml success.
     *
     * @return mixed
     */
    function xml_success($message = '接口成功')
    {
        $success = '<?xml version="1.0" encoding="utf-8"?>';
        $success .= '<response><state><code>1000</code><message>'.$message.'</message></state></response>';
        return $success;
    }
}
